/**
 * 时间格式化
 * @param {String} fmt "YYYY-mm-dd" 
 * @param {Date} date new Date()
 */
const dateFormat = function (fmt, date) {
    let ret;
    const opt = {
        "Y+": date.getFullYear().toString(), // 年
        "m+": (date.getMonth() + 1).toString(), // 月
        "d+": date.getDate().toString(), // 日
        "H+": date.getHours().toString(), // 时
        "M+": date.getMinutes().toString(), // 分
        "S+": date.getSeconds().toString() // 秒
        // 有其他格式化字符需求可以继续添加，必须转化成字符串
    };
    for (let k in opt) {
        ret = new RegExp("(" + k + ")").exec(fmt);
        if (ret) {
            fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
        };
    };
    return fmt;
}
// 保存获取历史至内存 使其仅读取一次 提高执行速度
var model = "";
// 保存手机信息至内存 同上
var systemInfo = null;
/**
 * 时间格式化 兼容苹果 仅字符串格式化兼容
 * @param {String} timeStr YYYY-MM-DD
 */
const newDate = function (timeStr) {
    if (!model) {
        // if(systemInfo)
        systemInfo = wx.getSystemInfoSync();
        model = systemInfo.model;
        console.log("model load");
    }
    const reg = /iPhone/ig;
    if (reg.test(model)) {
        timeStr = timeStr.replace(/-/g, "/");
    }
    return new Date(timeStr);
}
// wx.getMenuButtonBoundingClientRect()
var menuButtonObject = null;
// getHeaderStyle 的结果
var reobj = null;
/**
 * 读取header的style设置
 * height header内容的高 padding-top 顶部状态栏的高
 * @returns header 的 style 单位 px
 */
const getHeaderStyle = function () {
    if (reobj) return reobj;
    reobj = {
        height: "",
        paddingTop: "",
        paddingRight: "",
        navHeight: "",
        unit: "px"
    }
    if (!systemInfo)
        systemInfo = wx.getSystemInfoSync();
    if (!menuButtonObject)
        menuButtonObject = wx.getMenuButtonBoundingClientRect();
    var paddingTop = "",
        paddingRight = "",
        height = "";

    let statusBarHeight = systemInfo.statusBarHeight,
        navTop = menuButtonObject.top, //胶囊按钮与顶部的距离
        navHeight = menuButtonObject.height + (menuButtonObject.top <= 0 ? 0 : (menuButtonObject.top - statusBarHeight)) * 2; //导航高度

    paddingRight = systemInfo.screenWidth - menuButtonObject.left;
    paddingTop = systemInfo.statusBarHeight;
    height = navHeight;
    reobj.paddingTop = paddingTop;
    reobj.paddingRight = paddingRight;
    reobj.height = height;
    reobj.navHeight = paddingTop + height;
    paddingTop = undefined;
    height = undefined;
    return reobj;
}

var styleStr = null;
// var styleStrs = {};
/**
 * 获取 el 样式
 * @param bottomStyle 页面需要屏蔽的底部高度 {height: 100,unit: "px"}
 * @returns el的style字符串 例如: height:0px;
 */
const getElStyle = function (bottomStyle) {
    // console.log(styleStrs);
    if (!reobj) getHeaderStyle();
    // if(bottomStyle && styleStrs[bottomStyle]) return styleStrs[bottomStyle];
    if (!bottomStyle && styleStr) return styleStr;
    var str = "";
    if (!bottomStyle)
        str = "height: calc(100% - " + (reobj.navHeight + reobj.unit) + ");";
    else
        str = "height: calc(100% - " + (reobj.navHeight + reobj.unit) + " - " + (bottomStyle.height + bottomStyle.unit) + ");";
    str += "top: " + (reobj.navHeight + reobj.unit);
    // if(bottomStyle) styleStrs[bottomStyle] = str;
    // else styleStr = str;
    if (!bottomStyle) styleStr = str;
    console.log(str, reobj);
    return str;
};
const formatNumber = n => {
    n = n.toString()
    return n[1] ? n : '0' + n
}
//时间戳换算年月日时分秒
var stampFormatTime = function (number, format) {
    var formateArr = ['Y', 'M', 'D', 'h', 'm', 's'];
    var returnArr = [];
    var date = new Date(number);
    returnArr.push(date.getFullYear());
    returnArr.push(formatNumber(date.getMonth() + 1));
    returnArr.push(formatNumber(date.getDate()));
    returnArr.push(formatNumber(date.getHours()));
    returnArr.push(formatNumber(date.getMinutes()));
    returnArr.push(formatNumber(date.getSeconds()));
    for (var i in returnArr) {
        format = format.replace(formateArr[i], returnArr[i]);
    }
    return format;
}
/**
 * 生成列表
 * @param {Number} length 长度 int
 * @param {Function(int index)} fun 返回值作为数组的元素 
 */
const ListGenerate = function (length, fun) {
    var c = -1;
    var arr = [];
    while (++c < length) {
        arr.push(fun(c));
    }
    return arr;
};

/**
 * 元素获取data-*的数据
 * @param {*} e 
 */
const getDataSet = function (e) {
    var dataset = null;
    try {
        dataset = e.currentTarget.dataset;
    } catch (error) {
        dataset = e.target.dataset;
    }
    return dataset;
}
/**
 * 解蜜 用于Url传输
 * @param {String} string 
 */
const deCode = function (string) {
    if (!string) {
        throw Error("string is null");
    }
    return JSON.parse(decodeURIComponent(string));
}
/**
 * 加蜜 用于Url传输
 * @param {*} object 
 */
const enCode = function (object) {
    return encodeURIComponent(JSON.stringify(object));
}
/**
 * 提示框
 * @param {*} title 
 */
const showModal = function (title) {
    return new Promise((success, fail) => {
        wx.showModal({
            title: title || "提示",
            success(e) {
                if (e.confirm) {
                    success(true);
                } else {
                    fail(false);
                }
            },
            fail(e) {
                fail(e);
            }
        })
    });
}
/**
 * 提示
 * @param {String} title 
 */
const showToast = (title = "标题",mask = true) => new Promise((success,fail)=>{
    wx.showToast({
        title: title,
        duration: 1500,
        icon: "none",
        mask: mask,
    });
    setTimeout(() => {
        success();
    }, 1500);
});
module.exports = {
    showToast: showToast,
    showModal: showModal,
    deCode: deCode,
    enCode: enCode,
    getDataSet: getDataSet,
    ListGenerate: ListGenerate,
    dateFormat: dateFormat,
    newDate: newDate,
    getHeaderStyle: getHeaderStyle,
    getElStyle: getElStyle,
    stampFormatTime: stampFormatTime,
    formatNumber: formatNumber,
}